<template>
  <!-- 发药批次 -->
  <el-dialog
    title="选择药品批次和数量"
    :visible="value"
    width="1000px"
    custom-class="dialog-box"
    @close="onClose"
    @open="onOpen"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <table class="table-box">
      <thead>
        <tr>
          <th>药品名称</th>
          <th>规格</th>
          <th>有效期</th>
          <th>剩余数量</th>
          <th>批次</th>
          <th>数量</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="item in tableList">
          <tr v-for="(item2,index2) in item.list" :key="item2.id">
            <td
              v-if="index2==0"
              :rowspan="item.list.length"
              style="background-color: white !important;"
            >{{item2.sourceName}}（{{item2.useTotal}}{{item2.totalUnit|changeAssist(unitEnum)}}）</td>
            <td>
              <span v-if="item2.source==1">{{item2.specs}}</span>
              <span v-else>{{item2.packUnit|changeAssist(unitEnum)}}</span>
            </td>
            <td>
              {{item2.effectiveTime}}
              <span style="color:red;">{{item2.effectiveTime|toDisabled}}</span>
            </td>
            <td>{{item2|durgInventory(unitEnum)}}</td>
            <td>{{item2.lotNumber}}</td>
            <td>
              <el-input
                type="number"
                v-model.number="item2.sendNum"
                @change="onChangeNum(item2,item)"
                style="width:150px;"
              >
                <template slot="append">{{item2.totalUnit|changeAssist(unitEnum)}}</template>
              </el-input>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <span slot="footer">
      <el-button type="primary" :loading="btnLoading" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: ["value", "queryData"],
  filters: {
    toNumber(value) {
      return Number.parseInt(value);
    },
    toDisabled(value) {
      let d1 = new Date(value);
      let d2 = new Date();
      if (d1.getTime() - d2.getTime() > 0) {
        return "";
      } else {
        return "已过期";
      }
    }
  },
  data() {
    return {
      btnLoading: false,
      tableList: [],
      unitEnum: []
    };
  },
  created() {
    let th = this;
    th.getCommonConfigByKey("药品剂量单位").then(res => {
      th.unitEnum = res;
    });
  },
  methods: {
    getData(type, obj) {
      let th = this;
      let ids = [];
      obj.forEach(d => {
        ids.push(d.prescriptionDrugId);
      });
      let j = {
        type: type,
        prescriptionDrugIds: ids.join(",")
      };
      th.$api.getStockBatchByDrug(j).then(res => {
        if (res.executed) {
          if (res.data && res.data.length > 0) th.disposeData(res.data, obj);
        }
      });
    },
    onChangeNum(obj, parent) {
      const th = this;
      let useTotal = parent.useTotal; //总量
      let totalUnit = parent.totalUnit; //单位
      let sendNumTotal = 0; //发药总数量
      //判断是否可以拆分
      if (obj.sendNum < 0) {
        obj.sendNum = "";
        th.$message.warning("请输入大于0的数");
        return;
      }
      //判断是否可以拆分
      if (obj.isPiece == 1) {
        //判断发药单位是否大单位
        if (totalUnit == obj.packUnit) {
          if (obj.sendNum > obj.packNum) {
            obj.sendNum = "";
            th.$message.warning("数量超过库存");
            return;
          }
        } else {
          if (obj.sendNum > obj.usableNum) {
            obj.sendNum = "";
            th.$message.warning("数量超过库存");
            return;
          }
        }
      } else {
        //判断数量是否超过库存
        if (obj.sendNum > obj.packNum) {
          obj.sendNum = "";
          th.$message.warning("数量超过库存");
          return;
        }
      }

      parent.list.forEach(d => {
        sendNumTotal += d.sendNum || 0;
      });
      if (sendNumTotal > useTotal) {
        obj.sendNum = "";
        th.$message.warning("数量超过医生开单数量");
        return;
      }
    },
    //默认加载数量
    conutJS(ele, sendObj) {
      const th = this;
      if (ele.isPiece == 1) {
        //可拆分
        //判断医生发药单位（大单位）
        if (sendObj.totalUnit == ele.packUnit) {
          th.sendBigUnit(ele, sendObj);
        } else {
          //小单位
          th.sendSmallUnit(ele, sendObj);
        }
      } else {
        th.sendBigUnit(ele, sendObj);
      }
    },
    //小单位
    sendSmallUnit(ele, sendObj) {
      const th = this;
      //判断库存是否满足
      if (ele.usableNum > sendObj.useTotal) {
        th.$set(ele, "sendNum", sendObj.useTotal);
        sendObj.useTotal = 0;
      } else {
        //不满足
        let count = sendObj.useTotal - ele.usableNum;
        th.$set(ele, "sendNum", sendObj.useTotal - count);
        sendObj.useTotal = count;
      }
    },
    //大单位数量
    sendBigUnit(ele, sendObj) {
      const th = this;
      //判断库存是否满足
      if (ele.packNum > sendObj.useTotal) {
        th.$set(ele, "sendNum", sendObj.useTotal);
        sendObj.useTotal = 0;
      } else {
        //不满足
        let count = sendObj.useTotal - ele.packNum;
        th.$set(ele, "sendNum", sendObj.useTotal - count);
        sendObj.useTotal = count;
      }
    },
    //处理数据
    disposeData(data, obj) {
      let th = this;
      // let totalUnit = "";
      // if (obj && obj.length > 0) {
      //   totalUnit = obj[0].totalUnit;
      // }
      data.forEach((el, index) => {
        // el.totalUnit = totalUnit;
        //筛选数据
        let objDIndex = obj.findIndex(d => {
          return d.prescriptionDrugId == el.prescriptionDrugId;
        });
        if (objDIndex != -1) {
          let objD = obj[objDIndex];
          el.useTotal = objD.useTotal;
          el.totalUnit = objD.totalUnit;
          th.conutJS(el, objD);
          //这里删除之后不再渲染第二次
          // if (objD.useTotal == 0) {
          //   obj.splice(objDIndex, 1);
          // }
        }
        
        let j = {
          sourceName: el.sourceName,
          source: el.source,
          sourceId: el.sourceId,
          totalUnit: el.totalUnit,
          useTotal: el.useTotal,
          prescriptionDrugId: el.prescriptionDrugId,
          list: []
        };
        let fd = th.tableList.find(d => {
          if (d.source == el.source && d.sourceId == el.sourceId) return true;
          else return false;
        });
        if (fd) {
          fd.list.push(el);
        } else {
          j.list.push(el);
          th.tableList.push(j);
        }
      });
    },
    onSubmit() {
      let th = this;
      //循环判断是否输入值
      let medicalDrugSendDto = [];
      let prescriptionDrugIdList = []; //添加发药成功后的id
      let iserror = false;
      for (let i = 0; i < th.tableList.length; i++) {
        let data = th.tableList[i];
        let count = 0;
        prescriptionDrugIdList.push(data.prescriptionDrugId);
        for (let g = 0; g < data.list.length; g++) {
          let item = data.list[g];
          //判断是否有数量
          if (item.sendNum) {
            count += item.sendNum;
            // let queryData=th.queryData.
            let j = {
              prescriptionDrugId: item.prescriptionDrugId,
              drugId: item.sourceId,
              batchId: item.id,
              retailNum: item.sendNum,
              minUnit: item.totalUnit
            };
            medicalDrugSendDto.push(j);
          }
        }
        if (data.useTotal != count) {
          iserror = true;
          break;
        }
      }
      if (iserror) {
        th.$message.warning("发药数量与处方数量不匹配");
        return;
      }
      if (medicalDrugSendDto.length == 0) return;
      let j = {
        medicalDrugSendDto: JSON.stringify(medicalDrugSendDto)
      };
      th.btnLoading = true;
      th.$api
        .prescriptionSendDrug(j)
        .then(res => {
          if (res.executed) {
            th.$message.success("发药完成");
            th.$emit("success", prescriptionDrugIdList);
            th.onClose();
          } else {
            th.$message.error(res.message);
          }
          th.btnLoading = false;
        })
        .catch(() => {
          th.btnLoading = false;
        });
    },
    onOpen() {
      let th = this;
      th.$nextTick(function() {
        if (th.queryData.xy.length > 0) {
          let arr = th.queryData.xy.map(d => {
            return d;
          });
          th.getData(1, arr);
        }
        if (th.queryData.zy.length > 0) {
          let arr = th.queryData.zy.map(d => {
            return d;
          });
          th.getData(1, arr);
        }
      });
    },
    onClose() {
      let th = this;
      th.tableList = [];
      th.$emit("input", false);
    }
  }
};
</script>
